#!/bin/node

import * as fs from 'fs';
import langmap from '../channels/src/i18n/langmap.js';

let lines = '';
const langIDs = [];
const langFiles = {};
const langLabels = {};

fs.readdirSync('./channels/src/i18n').forEach(file => {
  if (file.endsWith('.json')) {
    const langID = file.substr(0, file.indexOf('.json'));

    // Skip default language
    if (langID === 'en') {
      return
    }
    
    langIDs.push(langID);
    lines += `import ${langID.replace('-', '')} from './${file}';\n`;
    langFiles[langID] = langID.replace('-', '');

    let m = langmap[langID]
    if (!m) {
      // We fallback to the language code prefix if we can't find a map.
      const id = langID.includes('-') ? langID.substr(0, langID.indexOf('-')) : langID;
      for (const k of Object.keys(langmap)) {
        if (k.startsWith(id)) {
          m = langmap[k];
          break;
        }
      }
    }

    langLabels[langID] = m ? m["nativeName"] : langID;
  }
});

lines += `
type TranslationsMap = {
    [id: string]: string,
};
`;
lines += `\nexport const langIDs = ${JSON.stringify(langIDs)};\n`
lines += `\nexport const langLabels = ${JSON.stringify(langLabels)};\n`

// To generate the file exports we need to do a bit more work to handle ids with dashes and also output a map of literals rather than strings.
lines += '\nexport const langFiles: {[langID: string]: TranslationsMap} = {' + Object.keys(langFiles).reduce((out, id, idx) => {
  if (id.includes('-')) {
    out += `'${id}':${langFiles[id]}`;
  } else {
    out += `${langFiles[id]}`;
  }

  if (idx !== (langIDs.length - 1)) {
    out += ',';
  }

  return out;
}, '') + '};';

const header = `// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.\n\n// DO NOT EDIT - This file is generated by gen_lang_imports through the gen-lang-imports script\n\n/* eslint-disable */\n\n`;

fs.writeFileSync('./channels/src/i18n/imports.ts', header+lines);

